package io.renren.modules.sp.controller;

import com.alibaba.excel.util.StringUtils;
import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.sp.dto.SpTeamDTO;
import io.renren.modules.sp.entity.SpTeamEntity;
import io.renren.modules.sp.entity.SpUserEntity;
import io.renren.modules.sp.excel.SpTeamExcel;
import io.renren.modules.sp.service.SpTeamService;
import io.renren.modules.sp.service.SpUserService;
import io.renren.modules.sys.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.*;


/**
* 领队
*
* @author Mark sunlightcs@gmail.com
* @since 3.0 2023-04-20
*/
@RestController
@RequestMapping("sp/spteam")
@Api(tags="领队")
public class SpTeamController{
    @Autowired
    private SpTeamService spTeamService;
    @Autowired
    private SpUserService spUserService;
    @Autowired
    private SysUserService sysUserService;


    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    @RequiresPermissions("sp:spteam:page")
    public Result<PageData<Map>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<Map> page = spTeamService.queryPage(params);
        return new Result<PageData<Map>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    //@RequiresPermissions("sp:spteam:info")
    public Result<Map<String,Object>> get(@PathVariable("id") Long id){
        Map<String,Object> data = spTeamService.queryById(id);

        return new Result<Map<String,Object>>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("sp:spteam:save")
    public Result save(@RequestBody SpTeamDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        spTeamService.save(dto);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @RequiresPermissions("sp:spteam:update")
    public Result update(@RequestBody SpTeamDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        spTeamService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("sp:spteam:delete")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        spTeamService.delete(ids);

        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @RequiresPermissions("sp:spteam:export")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        String userType = sysUserService.getSysUserType();
        //查询5w条
        params.put("limit", "50000");
        PageData<Map> page = spTeamService.queryPage(params);
        String matchId = (String)params.get("matchId");

        List<SpTeamExcel> list = new ArrayList<>();
        SpTeamExcel excel = new SpTeamExcel();
        for (Map map : page.getList()) {
            excel = new SpTeamExcel();
            //全部字段赋值
            excel.setId((Long) map.get("id"));
            excel.setTeamName((String) map.get("teamName"));
            excel.setCompany((String) map.get("company"));
            excel.setCompanyNo((String) map.get("companyNo"));
            excel.setProvince((String) map.get("provinceName"));
            excel.setCity((String) map.get("cityName"));
            excel.setLeader((String) map.get("leader"));
            excel.setSexStr((int) map.get("sex") == 1 ? "男" : "女");
            if(StringUtils.isBlank(matchId)) {
                String idType = (String) map.get("idType");
                if ("1".equals(idType)) {
                    excel.setIdType("居民身份证");
                } else if ("2".equals(idType)) {
                    excel.setIdType("临时身份证");
                } else if ("3".equals(idType)) {
                    excel.setIdType("港澳居民来往内地通行证");
                } else if ("4".equals(idType)) {
                    excel.setIdType("台湾居民来往大陆通行证");
                } else if ("5".equals(idType)) {
                    excel.setIdType("护照/其他");
                }
                excel.setIdCard((String) map.get("idCard"));
            }
            //非超管隐藏手机号
            if(!"0".equals(userType)){
                excel.setPhone("");
            }else {
                excel.setPhone((String) map.get("phone"));
            }
            excel.setAddress((String) map.get("address"));
            excel.setHeader((String) map.get("header"));
            excel.setEmpower((String) map.get("empower"));
            list.add( excel);
        }

        // 定义要排除的列名（字段名）
        Set<String> excludeColumnNames = new HashSet<>();
        if(StringUtils.isNotBlank(matchId)){
            excludeColumnNames.add("idCard");
            excludeColumnNames.add("idType");
            excludeColumnNames.add("header");
            excludeColumnNames.add("empower");
        }
        ExcelUtils.exportExcelToTarget(response, null, "领队", list, SpTeamExcel.class, excludeColumnNames);
    }

    /**
     * 启用/禁用
     * @param
     * @return
     */
    @PostMapping("updStatus")
    @ApiOperation("启用/禁用")
    @LogOperation("启用/禁用")
    public Result<SpTeamDTO> updStatus(@RequestBody SpTeamDTO dto){
        SpTeamEntity spTeamEntity = new SpTeamEntity();
        spTeamEntity.setId(dto.getId());
        spTeamEntity.setStatus(dto.getStatus());
        spTeamService.updateById(spTeamEntity);
        return new Result<SpTeamDTO>();
    }

    /**
     * 直通
     * @param
     * @return
     */
    @PostMapping("updIspass")
    public Result<SpTeamDTO> updIspass(@RequestBody SpTeamDTO dto){
        SpTeamEntity spTeamEntity = new SpTeamEntity();
        spTeamEntity.setId(dto.getId());
        spTeamEntity.setIsPass(dto.getIsPass());
        spTeamService.updateById(spTeamEntity);
        return new Result<SpTeamDTO>();
    }

    /**
     * 修改老师
     * @param
     * @return
     */
    @PostMapping("updTeacherFlag")
    public Result<SpTeamDTO> updTeacherFlag(@RequestBody SpTeamDTO dto){
        SpTeamEntity spTeamEntity = new SpTeamEntity();
        spTeamEntity.setId(dto.getId());
        spTeamEntity.setUpdTeacherFlag(dto.getUpdTeacherFlag());
        spTeamService.updateById(spTeamEntity);
        return new Result<SpTeamDTO>();
    }

    /**
     * 下载承诺书
     */
    @GetMapping("downloadPromissFile")
    public Result<String> downloadPromissFile(@RequestParam Map<String, Object> params, HttpServletResponse response) {
        return spTeamService.downloadPromissFile(params, response);
    }

    //全部关闭
    @PostMapping("closeAll")
    public Result<String> closeAll(@RequestBody Map<String, Object> params) {
        spTeamService.closeAll();
        return new Result<String>();
    }

}
